//
//  ProfileViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by JennyShi on 2018/4/23.
//  Copyright © 2018年 杜洁鹏. All rights reserved.
//

import UIKit
import os.log
import Hyphenate
import MobileCoreServices
import MBProgressHUD
import Alamofire

class ProfileViewController: UIViewController,UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //profile各个属性的值和临时属性
    var username = ""
    var city = ""
    var firstName = ""
    var middleName = ""
    var lastName = ""
    var country = ""
    var phone = ""
    var phoneCode = ""
    //不显示
    var deviceType = ""
    var dob = ""
    var dobDate = Date() - 20 * 365 * 24 * 3600
    var gender = ""
    //不显示
    var password = ""
    var email = ""
    var emailCode = ""
    //不显示
    var deviceToken = ""
    //不显示，存取头像文件用
    var imagePath = ""
    var imageLocalPath = ""
    var oldImage = UIImage()
    var newImage = UIImage()

    //自定义控件变量：label、textField、textView、button
    var ownerLabel = UILabel()
    var eownerNameLabel = UILabel()
    var cityLabel = UILabel()
    var cityField = UITextField()
    var firstNameLabel = UILabel()
    var firstNameView = UITextField()
    var middleNameLabel = UILabel()
    var middleNameView = UITextField()
    var lastNameLabel = UILabel()
    var lastNameView = UITextField()
    var countryLabel = UILabel()
    var countryButton = UIButton()
    var countryView = UITextField()
    var dobLabel = UILabel()
    var dobButton = UIButton()
    var genderType = UILabel()
    var genderTypeButton = UIButton()
    var myImageLabel = UILabel()
    var myImageView: UIImageView = UIImageView()
    var gesture = UITapGestureRecognizer()
    var phoneLabel = UILabel()
    var phoneNumberLabel = UILabel()

    //选择dob用的临时UIKits变量
    var dobSelectView = UIView()
    var datePicker = UIDatePicker()
    var dobSelectButton = UIButton()
    
    //屏幕不含状态栏的大小
    var screenX : Int = 0
    var screenY : Int = 0
    var screenWidth : Int = 0
    var screenHeight : Int = 0
    
    var widthEverage : Int = 0
    var heightEverage : Int = 0
    
    //控制状态变量
    var alertCancel = 0
    var alertOk = 0
    var requestHowManyTimes = 0
    var uploadCompleted = true
    var avatarChanged = false

    //临时变量
    var statusPara = StatusPara(hasFriend:false,friendOwner:"",loginOwner:"",sourceViewControllerType:1,dateTitle:"",date:Date(),calendarTypeNumber:0,matchOrFree:0,languageNow:"")
    var loginOwner = ""
    var friendOwner = ""
    var date = Date()
    var dformatter = DateFormatter()
    var dateTitle = ""
    
    @objc func keyboardWillShow(sender: NSNotification) {
        self.view.frame.origin.y = -150 // Move view 150 points upward
    }
    
    @objc func keyboardWillHide(sender: NSNotification) {
        self.view.frame.origin.y = 0 // Move view to original position
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillShow(sender:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillHide(sender:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

        let languageNow = EnStatic.languegeUsing()
        loginOwner = EMClient.shared().currentUsername
        dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy-MM-dd"
        dateTitle = dformatter.string(from: date)
        statusPara = StatusPara(hasFriend:(!friendOwner.isEmpty),friendOwner:friendOwner,loginOwner:loginOwner,sourceViewControllerType:1,dateTitle:dateTitle,date:date,calendarTypeNumber:0,matchOrFree:0,languageNow:languageNow)

        let selfViewBounds:CGRect = self.view.bounds
        let navigationHeight = UIApplication.shared.statusBarFrame.height
        
        screenX = Int(selfViewBounds.origin.x)
        screenY = Int(selfViewBounds.origin.y + navigationHeight)
        screenHeight = Int(selfViewBounds.height)
        screenWidth = Int(selfViewBounds.width)
        
        //自定义导航栏左侧的cancel按钮和右侧的save按钮
        let cancelButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Back"), style: .plain, target: self, action: #selector(cancelButtonClicked))
        self.navigationItem.leftBarButtonItem = cancelButtonItem
        
        let save000ButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Save"), style: .plain, target: self, action: #selector(saveButtonBigClicked))
        self.navigationItem.rightBarButtonItem = save000ButtonItem
        
        //头像本地临时存储路径
        let rootPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                           .userDomainMask, true)[0] as String
        imageLocalPath = "\(rootPath)/selectedImage.jpg"

        //设置无头像状态
        self.uploadCompleted = true
        self.imagePath = ""
        self.requestHowManyTimes = 0

        //获取旧的profile，包括头像
        getProfile()
        
        //重新定义各个显示控件的尺寸、位置、颜色、形状等属性
        adapterUIAttribute()
        
        //设置textField和textView的代理
        countryView.delegate = self
        countryView.returnKeyType = UIReturnKeyType.done
        cityField.delegate = self
        cityField.returnKeyType = UIReturnKeyType.done
        firstNameView.delegate = self
        firstNameView.returnKeyType = UIReturnKeyType.done
        middleNameView.delegate = self
        middleNameView.returnKeyType = UIReturnKeyType.done
        lastNameView.delegate = self
        lastNameView.returnKeyType = UIReturnKeyType.done

        //设置选择生日的窗口和标题
        setDateTimePicker()
        
        //设置save按钮状态
        updateSaveButtonState()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func myAlert(message000 : String) {
        let alertController = UIAlertController(title: "",message: EnStatic.getWord(keyWord: message000), preferredStyle: .alert)
        let okAction = UIAlertAction(title: EnStatic.getWord(keyWord: "OK"), style: .default, handler: {
            action in
            print("ok clicked")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    //MARK: 导航栏左上角的cancel返回键和右上角的save返回键
    @objc func cancelButtonClicked() {
        if let owningNavigationController = self.navigationController{
            owningNavigationController.popViewController(animated: true)
        }else {
            fatalError("The ViewController is not inside a navigation controller.")
        }
    }
    
    @objc func saveButtonBigClicked() {
        uploadImage()
    }
    
    //获取旧的Profile信息
    func getProfile() {

        //根据loginOwner合成urlstr
        var urlString : String = ""
        
        urlString = "profile?username=" + loginOwner
        
        let cuHTTP = CUHTTP.instance()
        
        cuHTTP.makeGetData(url: urlString, success: {response in
            print("Response String: \(String(describing: response?.result.value))")
            print(response?.response?.statusCode ?? "??")      //成功时，返回200
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: Any]
                print(json ?? "??")
                let allEvents = json!["user"] as Any
                print(allEvents)
                
                let loopE = allEvents as! [String: Any]
                if let tmpStr0 = loopE["username"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.username = tmpStr1
                        self.eownerNameLabel.text = self.username
                    }
                }
                if let tmpStr0 = loopE["city"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.city = tmpStr1
                        self.cityField.text = self.city
                    }
                }
                if let tmpStr0 = loopE["firstName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.firstName = tmpStr1
                        self.firstNameView.text = self.firstName
                    }
                }
                if let tmpStr0 = loopE["middleName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.middleName = tmpStr1
                        self.middleNameView.text = self.middleName
                    }
                }
                if let tmpStr0 = loopE["lastName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.lastName = tmpStr1
                        self.lastNameView.text = self.lastName
                    }
                }
                if let tmpStr0 = loopE["country"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let tmpStr2 = EnStatic.getWord(keyWord: tmpStr1)
                        self.country = tmpStr2
                        self.countryButton.setTitle(self.country, for: .normal)
                        self.countryView.text = self.country
                    }
                }
                if let tmpStr0 = loopE["deviceType"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.deviceType = tmpStr1
                    }
                }
                if let tmpStr0 = loopE["dob"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.dob = tmpStr1
                        self.dobButton.setTitle(self.dob, for: .normal)
                        //在此设置生日选择器的初值
                        let nsDob = self.dob as NSString
                        if nsDob.length == 10 {
                            let formatter = DateFormatter()
                            formatter.dateFormat = "yyyy-MM-dd"
                            self.dobDate = formatter.date(from: self.dob)!
                            self.datePicker.setDate(self.dobDate, animated: true)
                        }
                    }
                }
                if let tmpStr0 = loopE["gender"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let tmpStr2 = EnStatic.getWord(keyWord: tmpStr1)
                        self.gender = tmpStr2
                        self.genderTypeButton.setTitle(self.gender, for: .normal)
                    }
                }
                if let tmpStr0 = loopE["password"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.password = tmpStr1
                    }
                }
                if let tmpStr0 = loopE["phone"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.phone = tmpStr1
                        self.phoneNumberLabel.text = self.phone
                    }
                }
                if let tmpStr0 = loopE["countryCode"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.phoneNumberLabel.text = "(+" + tmpStr1 + ")" + (self.phoneNumberLabel.text)!
                    }
                }
                if let tmpStr0 = loopE["deviceToken"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.deviceToken = tmpStr1
                    }
                }
                //读取头像文件全路径
                if let tmpStr0 = loopE["imageName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.imagePath = tmpStr1
                        self.myImageView.imageWithUsername(username: EMClient.shared().currentUsername, placeholderImage: nil)
                    }
                    
                }
                self.updateSaveButtonState()
                
            }
            },
                           failure:{ response in
                            print(response ?? " ")
                            self.myAlert(message000: EnStatic.getWord(keyWord: "get data failed"))
        }
        )
        
    }
    //提交新的profile信息
    func postProfile() {
        
        city = cityField.text!
        country = countryView.text!
        firstName = firstNameView.text!
        middleName = middleNameView.text!
        lastName = lastNameView.text!
        
        let cuHTTP = CUHTTP.instance()
        
        let urlString = "profile?username=" + loginOwner

        var parameters: [String: Any]
        
        parameters = [
            "username" : username,
            "city" : city,
            "firstName" : firstName,
            "middleName" : middleName,
            "lastName" : lastName,
            "country" : country,
            "dob" : dob,
            "gender" : EnStatic.chnToEnWord(keyWord: gender),
            "imageName" : imagePath
        ]

        print(parameters)
        
        cuHTTP.makePostData(url: urlString, parameters: parameters,
                            success: {response in
                                print(response?.response?.statusCode ?? "??")      //成功时，返回200
                                let defaults = UserDefaults.standard
                                defaults.set(self.firstName, forKey: self.username+"_nickname")
                                self.navigationController?.popViewController(animated: true)
                                
                               
        } ,
                            failure: {response in
                                self.myAlert(message000: EnStatic.getWord(keyWord: "save failed"))
        }
        )
        
    }
    
    //上传图片
    func uploadImage() {
        if(self.avatarChanged){
            let image =  UIImage(contentsOfFile: imageLocalPath)
            let imgData = UIImageJPEGRepresentation(image!, 0.2)!
            let parameters = ["username": EMClient.shared().currentUsername,"lang":Locale.current.languageCode]
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(imgData, withName: "image", fileName: "user_profiel_image.jpeg", mimeType: "image/jpeg")
                for (key, value) in parameters {
                    multipartFormData.append((value?.data(using: String.Encoding.utf8))!, withName: key)
                }
            }, to: CUHTTP.URL.ROOT + "profileImage/")
            { (result) in
                switch result {
                case .success(let upload, _, _):
                    
                    upload.uploadProgress(closure: { (progress) in
                        //Print progress
                    })
                    
                    upload.responseString { response in
                        print(response.result)
                        if response.result.isSuccess {
                            print(response.response?.allHeaderFields ?? " ")
                            let data = response.response! as HTTPURLResponse
                            let field = data.allHeaderFields["Location"] as! String
                            
                            let defaults = UserDefaults.standard
                            defaults.set(CUHTTP.URL.ROOT + field, forKey: EMClient.shared().currentUsername+"_avatar")
                        }
                        self.postProfile()
                    }
                    
                case .failure(let encodingError): break
                    
                }
            }
            
        }else{
            self.postProfile()
        }
        
    }
    
    // Disable the Save button if the necessary field is empty.
    private func updateSaveButtonState() {
        navigationItem.rightBarButtonItem?.isEnabled = true
    }

    //MARK: 设置生日
    func setDateTimePicker() {
        dobSelectView.isHidden = true
    }
    
    //选定生日的ok按钮
    @objc func okButtonTapped() {
        dobSelectView.isHidden = true
    }
    
    //日期选择器响应方法
    @objc func dateChanged(datePicker : UIDatePicker){
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        dob = formatter.string(from: datePicker.date)
        dobButton.setTitle(dob, for: UIControlState.normal)
    }
    
    //设置生日
    @objc func dateSet() {
        dobSelectView.isHidden = false
        datePicker.isHidden = false
    }
    
    @objc func genderTypeButtonClicked() {
        if gender.compare(EnStatic.getWord(keyWord: "male")).rawValue == 0 {
            gender = EnStatic.getWord(keyWord: "female")
        } else {
            gender = EnStatic.getWord(keyWord: "male")
        }
        genderTypeButton.setTitle(gender, for: .normal)
    }
    
    //MARK: UITextFieldDelegate
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Disable the Save button while editing.
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        textField.resignFirstResponder()
        updateSaveButtonState()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // Hide the keyboard.
        textField.resignFirstResponder()
        return true
    }
    
    //MARK: UIImagePickerControllerDelegate
    
    @objc func imageViewGestureTapped() {
        
        // UIImagePickerController is a view controller that lets a user pick media from their photo library.
        let imagePickerController = UIImagePickerController()
        
        // Only allow photos to be picked, not taken.
        imagePickerController.sourceType = .photoLibrary
        
        // Make sure ViewController is notified when the user picks an image.
        imagePickerController.delegate = self
        
        present(imagePickerController, animated: true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        // Dismiss the picker if the user canceled.
        dismiss(animated: true, completion: nil)
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard var selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        
        // Dismiss the picker.
        dismiss(animated: true, completion: nil)
        
        //压缩图片到36k左右
        let img = selectedImage.imageByScalingAndCroppingForSize(targetSize: CGSize.init(width: 120, height: 120))
        selectedImage = img

        var KB = 0.0
        if let imageData = UIImagePNGRepresentation(selectedImage) {
            let bytes = imageData.count
            KB = Double(bytes) / (1024.0*1024.0) // Note the difference
        }
        
        //2M
        if KB >= 2 {
            //图片太大
            myAlert(message000: EnStatic.getWord(keyWord: "avatar bigger than 2M"))
            //设置无头像状态
            uploadCompleted = true
            requestHowManyTimes = 0
        } else {
            // Set photoImageView to display the selected image.
            myImageView.image = selectedImage
            
            //将选择的图片保存到Document目录下
            let fileManager = FileManager.default
            let imageData = UIImageJPEGRepresentation(selectedImage, 1.0)
            fileManager.createFile(atPath: imageLocalPath, contents: imageData, attributes: nil)

            //上传图片，并获得文件全路径imagePath
            uploadCompleted = false
            
            //标记头像已经更改，存盘时同步到easeMob的profile时用
            avatarChanged = true

            //新头像，同步到easeMob的profile中
            newImage = selectedImage
        }
        
    }
    
    // MARK: - 重新定义各个显示控件的尺寸、位置、颜色、形状等属性
    func adapterUIAttribute() {
        
        var tmpY = 0
        var tmpWidth = 0
        var labelWidth = 0
        
        let tmpHeight = 30
        let fromX = 10
        
        let navigationBarHeight = 40
        let toolBarHeight = 60
        
        //最小的iphone宽度也不会越界，即verticalAdd一定大于零
        let verticalAdd = (screenHeight - screenY - toolBarHeight - 13 * tmpHeight)/12

        //字号
        let funtSize : CGFloat = 14.0
        
        //边框宽度和圆角半径
        let tmpBorder : CGFloat = 1.0
        let tmpCornerRadius : CGFloat = 4.0
        
        //重新定义各个控件的尺寸
        tmpY = screenY + navigationBarHeight + verticalAdd
        labelWidth = 90
        tmpWidth = tmpHeight * 2

        myImageLabel.frame = CGRect(x: fromX, y: tmpY + tmpHeight, width: labelWidth, height: tmpHeight)
        myImageLabel.text = EnStatic.getWord(keyWord: "Avatar")
        myImageLabel.textColor = UIColor.black
        myImageLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        myImageView.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight*2)
        myImageView.layer.borderWidth = tmpBorder
        myImageView.layer.cornerRadius = tmpCornerRadius * 2
        gesture = UITapGestureRecognizer(target: self, action: #selector(imageViewGestureTapped))
        myImageView.addGestureRecognizer(gesture)
        myImageView.isUserInteractionEnabled = true
        
        tmpWidth = screenWidth - (3 * fromX) - labelWidth
        tmpY = screenY + navigationBarHeight + 2 * verticalAdd + 2 * tmpHeight
        ownerLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        ownerLabel.text = EnStatic.getWord(keyWord: "User Name")
        ownerLabel.textColor = UIColor.black
        ownerLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        eownerNameLabel.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
//        eownerNameLabel.padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        eownerNameLabel.text = loginOwner
        eownerNameLabel.font = UIFont.systemFont(ofSize: funtSize)
        eownerNameLabel.layer.borderWidth = tmpBorder
        eownerNameLabel.layer.borderColor = UIColor.lightGray.cgColor
        eownerNameLabel.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 3 * verticalAdd + 3 * tmpHeight
        phoneLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        phoneLabel.text = EnStatic.getWord(keyWord: "Phone")
        phoneLabel.textColor = UIColor.black
        phoneLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        phoneNumberLabel.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
//        phoneNumberLabel.padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        phoneNumberLabel.text = phone
        phoneNumberLabel.font = UIFont.systemFont(ofSize: funtSize)
        phoneNumberLabel.layer.borderWidth = tmpBorder
        phoneNumberLabel.layer.borderColor = UIColor.lightGray.cgColor
        phoneNumberLabel.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 4 * verticalAdd + 4 * tmpHeight
        firstNameLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        firstNameLabel.text = EnStatic.getWord(keyWord: "First Name")
        firstNameLabel.textColor = UIColor.black
        firstNameLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        firstNameView.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height:  tmpHeight)
//        firstNameView.setLeftPaddingPoints(5)
//        firstNameView.setRightPaddingPoints(5)
        firstNameView.text = firstName
        firstNameView.font = UIFont.systemFont(ofSize: funtSize)
        firstNameView.layer.borderWidth = tmpBorder
        firstNameView.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 5 * verticalAdd + 5 * tmpHeight
        middleNameLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        middleNameLabel.text = EnStatic.getWord(keyWord: "Middle Name")
        middleNameLabel.textColor = UIColor.black
        middleNameLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        middleNameView.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height:  tmpHeight)
//        middleNameView.setLeftPaddingPoints(5)
//        middleNameView.setRightPaddingPoints(5)
        middleNameView.text = middleName
        middleNameView.font = UIFont.systemFont(ofSize: funtSize)
        middleNameView.layer.borderWidth = tmpBorder
        middleNameView.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 6 * verticalAdd + 6 * tmpHeight
        lastNameLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        lastNameLabel.text = EnStatic.getWord(keyWord: "Last Name")
        lastNameLabel.textColor = UIColor.black
        lastNameLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        lastNameView.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
//        lastNameView.setLeftPaddingPoints(5)
//        lastNameView.setRightPaddingPoints(5)
        lastNameView.text = lastName
        lastNameView.font = UIFont.systemFont(ofSize: funtSize)
        lastNameView.layer.borderWidth = tmpBorder
        lastNameView.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 7 * verticalAdd + 7 * tmpHeight
        genderType.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        genderType.text = EnStatic.getWord(keyWord: "Gender")
        genderType.textColor = UIColor.black
        genderType.font=UIFont.systemFont(ofSize: funtSize)
        
        tmpWidth = screenWidth -  (3 * fromX) - labelWidth
        genderTypeButton.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
        genderTypeButton.contentHorizontalAlignment = .left
        genderTypeButton.titleEdgeInsets.left = 5
        genderTypeButton.setTitle(gender, for: .normal)
        genderTypeButton.addTarget(self, action: #selector(genderTypeButtonClicked), for: UIControlEvents.touchUpInside)
        genderTypeButton.setTitleColor(UIColor.black, for: .normal)
        genderTypeButton.setTitleColor(UIColor.green, for: .highlighted) //触摸状态下文字的颜色
        genderTypeButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        genderTypeButton.layer.borderWidth = tmpBorder
        genderTypeButton.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 8 * verticalAdd + 8 * tmpHeight
        dobLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        dobLabel.text = EnStatic.getWord(keyWord: "DoB")
        dobLabel.textColor = UIColor.black
        dobLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        tmpWidth = screenWidth -  (3 * fromX) - labelWidth
        dobButton.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
        dobButton.contentHorizontalAlignment = .left
        dobButton.titleEdgeInsets.left = 5
        dobButton.setTitle(dob, for: .normal)
        dobButton.addTarget(self, action: #selector(dateSet), for: UIControlEvents.touchUpInside)
        dobButton.setTitleColor(UIColor.black, for: .normal)
        dobButton.setTitleColor(UIColor.green, for: .highlighted) //触摸状态下文字的颜色
        dobButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        dobButton.layer.borderWidth = tmpBorder
        dobButton.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 9 * verticalAdd + 9 * tmpHeight
        cityLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        cityLabel.text = EnStatic.getWord(keyWord: "City")
        cityLabel.textColor = UIColor.black
        cityLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        cityField.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
//        cityField.setLeftPaddingPoints(5)
//        cityField.setRightPaddingPoints(5)
        cityField.text = city
        cityField.font = UIFont.systemFont(ofSize: funtSize)
        cityField.layer.borderWidth = tmpBorder
        cityField.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 10 * verticalAdd + 10 * tmpHeight
        countryLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        countryLabel.text = EnStatic.getWord(keyWord: "Country")
        countryLabel.textColor = UIColor.black
        countryLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        tmpWidth = screenWidth -  (3 * fromX) - labelWidth
        countryView.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width:tmpWidth, height: tmpHeight)
//        countryView.setLeftPaddingPoints(5)
//        countryView.setRightPaddingPoints(5)
        countryView.text = country
        countryView.font = UIFont.systemFont(ofSize: funtSize)
        countryView.layer.borderWidth = tmpBorder
        countryView.layer.cornerRadius = tmpCornerRadius
        
        //选择生日用的临时UIKits变量
        dobSelectView = UIView(frame: CGRect(x: 30, y: 100, width: screenWidth - 60, height: 300))
        datePicker = UIDatePicker(frame: CGRect(x:30, y:0, width:screenWidth - 100, height:240))
        datePicker.setDate(dobDate, animated: true)
        dobSelectButton.frame = CGRect(x: screenWidth/2 - 60, y: 240, width: 60, height: 30)
        dobSelectView.layer.borderWidth=1//边框宽度
        dobSelectView.layer.cornerRadius=10//边框弧度
        dobSelectView.backgroundColor = UIColor.lightGray
        
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            datePicker.locale = NSLocale(localeIdentifier: "en_US") as Locale
            datePicker.datePickerMode = UIDatePickerMode.date
        } else {
            datePicker.locale = Locale(identifier: "zh_CN")
            datePicker.datePickerMode = UIDatePickerMode.date
        }
        datePicker.setValue(UIColor.black, forKey: "textColor")
        datePicker.addTarget(self, action: #selector(dateChanged),
                             for: .valueChanged)
        
        dobSelectButton.setTitle(EnStatic.getWord(keyWord: "OK"), for: UIControlState.normal)
        dobSelectButton.addTarget(self, action: #selector(okButtonTapped), for: .touchUpInside)
        
        dobSelectView.addSubview(datePicker)
        dobSelectView.addSubview(dobSelectButton)
        
       //关联控件以显示
        self.view.addSubview(ownerLabel)
        self.view.addSubview(eownerNameLabel)
        self.view.addSubview(cityLabel)
        self.view.addSubview(cityField)
        self.view.addSubview(firstNameLabel)
        self.view.addSubview(firstNameView)
        self.view.addSubview(middleNameLabel)
        self.view.addSubview(middleNameView)
        self.view.addSubview(lastNameLabel)
        self.view.addSubview(lastNameView)
        self.view.addSubview(countryLabel)
        self.view.addSubview(countryView)
        self.view.addSubview(dobLabel)
        self.view.addSubview(dobButton)
        self.view.addSubview(genderType)
        self.view.addSubview(genderTypeButton)
        self.view.addSubview(myImageLabel)
        self.view.addSubview(myImageView)
        self.view.addSubview(phoneLabel)
        self.view.addSubview(phoneNumberLabel)
        self.view.addSubview(dobSelectView)
        
    }

}

